package cn.lzm.basic.interceptor;

import cn.lzm.user.domain.Logininfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.concurrent.TimeUnit;
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      // 获取token中的值
        String token = request.getHeader("token");
        // 判断token是不是空
        if (StringUtils.isNotBlank(token)) {
          Logininfo logininfo   =(Logininfo) redisTemplate.opsForValue().get(token);
          if (null != logininfo){
              // 重置时间
              redisTemplate.expire(token,30, TimeUnit.MINUTES);
              return true;
          }
        }
        // 为空 我们要返回 {"success":false,"resultObj":"nologin"}
        // 但是只能返回boolean 所以需要直接使用流 写到前端取
        // 3.1.设置编码字符集
        response.setCharacterEncoding("UTF-8");
        // 3.2.设置响应参数类型为JSON
        response.setContentType("application/json;charset=UTF-8");
        // 3.3 获取获取打印流，设置响应数据
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"resultObj\":\"noLogin\"}");
        // 3.4.刷新、关流
        writer.flush();
        writer.close();
        return false;
    }
}
